from flask import redirect,request,make_response,url_for,g
from model import *

def ModelName(func):
    def wrapper():
        '''处理业务'''
    wrapper.__name__=func.__name__#!防止视图函数名相同
    return wrapper

def validate(func):
    def wrappers():
        cookie=request.cookies.get("Dom_cookie")
        ok,result=select("select count(*) as counts from users where Cookie='{}'".format(cookie))
        _,Identity=select("select Identity from users where Cookie='{}'".format(cookie))
        if ok:
            print(result)
            if result[0]['counts']>0:
                g.Is_Blogger=Identity[0]['Identity']
                return func()
            else:
                return redirect(url_for('html.login'))#^如果查询不到所携带的cookie则视为未登录，重定向到登录界面
        else:
            response=make_response({"status":403,"message":"Invalid cookie"})
            response.status=403
            return response
    wrappers.__name__=func.__name__#^防止视图函数名重复
    return wrappers

def Is_Blogger(func):
    def wrapper():
        cookie=request.cookies.get("Dom_cookie")
        ok,result=select("select Identity from users where Cookie='{}'".format(cookie))
        if ok:
            if result[0]['Identity']==1:#^用户鉴权，仅博主可继续执行业务
                return func()
            else:
                return redirect(url_for('html.index'))#^否则重定向到首页
        else:
            response=make_response({"status":403,"message":"Invalid cookie"})
            response.status=403
            return response
    wrapper.__name__=func.__name__#!防止视图函数名相同
    return wrapper